<?php
class RecommendTeacher extends AppModel {
	var $name = 'RecommendTeacher';
	var $useTable = 'recommend_teachers';
	var $primaryKey = 'id';

	/**
	 * get max Rank
	 * @return int
	 */
	function _getMaxRank() {
		return $this->field('rank', null, 'rank DESC');
	}
	
	/**
	 * check is exists user in recommend teacher
	 * @param int $userId
	 * @return boolean
	 */
	function _isRecommendTeacher($userId) {
		$count = $this->find('count', array(
			'conditions' => array(
				$this->alias . '.user_id' => $userId
			)
		));
		if($count > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * @param int $userId
	 * @return int
	 */
	function add($userId) {
		App::import('model', 'User');
		$user = new User();
		if($user->isValidUser($userId)){
			if(!$this->_isRecommendTeacher($userId)){
				$rank = $this->_getMaxRank();
				$rank ++;
				$data = array(
					'user_id' => $userId,
					'rank' => $rank
				);
				if($this->save($data)){
					return 1;
				}
				return -1;
			}
			return 0;
		}
		return -1;
	}
	
	/**
	 * delete
	 * @param int $id
	 * @return type
	 */
	function remove($id) {
		if(intval($id)){
			return $this->delete($id);
		}
		return false;
	}
	
	/**
	 * is recommend Id
	 */
	function isRecommendTeacherId($id){
		$count = $this->find('count', array(
			'conditions' => array(
				$this->alias . '.id' => $id
			)
		));
		if($count > 0)
			return true;
		return false;
	}
}